package com.shanshan.crowd.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shanshan.crowd.constant.CrowdConstant;
import com.shanshan.crowd.entity.Admin;
import com.shanshan.crowd.entity.AdminExample;
import com.shanshan.crowd.exception.LoginAcctAlreadyInUpdateException;
import com.shanshan.crowd.exception.LoginAcctAlreadyInUseException;
import com.shanshan.crowd.exception.LoginAlreadyInUseException;
import com.shanshan.crowd.exception.LoginFailedException;
import com.shanshan.crowd.mapper.AdminMapper;
import com.shanshan.crowd.service.api.AdminService;
import com.shanshan.crowd.util.CrowdUtil;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Description
 * @ClassName AdminServiceImpl
 * @Author 山山大魔王
 * @Date 2022/7/19 17:08
 * @Version 1.0
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Resource
    private AdminMapper adminMapper;

    Logger logger=LoggerFactory.getLogger(AdminServiceImpl.class);

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void saveAdmin(Admin admin) {
        // 生成当前系统时间
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = format.format(date);

        admin.setCreateTime(createTime);

        //针对密码进行加密
        String source = admin.getUserPswd();
//        String encoded = CrowdUtil.md5(source);
        String encoded = passwordEncoder.encode(source);
        admin.setUserPswd(encoded);

        try {
            adminMapper.insert(admin);
        } catch (Exception exception) {
            exception.printStackTrace();

            if (exception instanceof DuplicateKeyException){
                // 抛出自定义的LoginAlreadyInUseException异常
                throw new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
            throw exception;
        }

    }

    @Override
    public Object getAll() {
        return adminMapper.selectByExample(new AdminExample());
    }

    @Override
    public Admin getAdminByLoginAcct(String loginAcct, String userPswd) {

        // 0.检查传入的字符串是否合法
        if ( loginAcct == null || loginAcct.length() == 0 || userPswd == null || userPswd.length() == 0){
            throw new LoginFailedException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }

        // 1.根据登录账号查询Admin对象
        // ①创建AdminExample对象
        AdminExample adminExample = new AdminExample();

        // ②创建Criteria对象
        AdminExample.Criteria criteria = adminExample.createCriteria();

        // ③在Criteria对象中封装查询条件
        criteria.andLoginAcctEqualTo(loginAcct);

        // ④调用AdminMapper的方法执行查询
        List<Admin> list = adminMapper.selectByExample(adminExample);

        // 2.判断Admin对象是否为null
        if (list == null || list.size() == 0){
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        if (list.size()>1){
            throw new RuntimeException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }

        Admin admin = list.get(0);

        // 3.如果为null抛出异常
        if (admin == null){
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        // 4.如果不为null则将数据密码从admin对象中取出
        String userPswdDB = admin.getUserPswd();

        // 5.将表单提交的明文密码进行加密
        String userPswdForm = CrowdUtil.md5(userPswd);

        // 6.对密码进行比较
        if (!Objects.equals(userPswdDB, userPswdForm)){
            // 7.不一致抛出异常
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        // 8.一致返回admin对象
        return admin;
    }

    @Override
    public Admin getAdminByLoginAcct(String username) {

        AdminExample example = new AdminExample();

        AdminExample.Criteria criteria = example.createCriteria();

        criteria.andLoginAcctEqualTo(username);

        List<Admin> list = adminMapper.selectByExample(example);

        Admin admin = list.get(0);

        return admin;
    }

    @Override
    public PageInfo<Admin> getAdminPage(String keyword, Integer pageNum, Integer pageSize) {
        // 1.开启分页功能
        PageHelper.startPage(pageNum, pageSize);

        // 2.查询admin数据
        List<Admin> adminList = adminMapper.selectAdminListByKeyword(keyword);

        // 打印adminList的全类名
        logger.debug("adminList的全类名是：{}", adminList.getClass().getName());

        // 3.为了方便页面使用将adminList封装为PageInfo
        PageInfo<Admin> pageInfo = new PageInfo<>(adminList);

        return pageInfo;
    }

    @Override
    public void remove(Integer adminId) {
        adminMapper.deleteByPrimaryKey(adminId);
    }

    @Override
    public Admin getAdminById(Integer adminId) {
        return adminMapper.selectByPrimaryKey(adminId);
    }

    @Override
    public void update(Admin admin) {
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception exception) {
            logger.debug("异常信息{}",exception.getMessage());
            if (exception instanceof DuplicateKeyException){
                throw new LoginAcctAlreadyInUpdateException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }
    }

    @Override
    public void saveRelationship(Integer adminId, List<Integer> roleIdList) {

        // 1.更具adminId 删除旧的关联关系数据
        adminMapper.deleteOldRelationsip(adminId);
        // 2.更具roleIdList和adminId保存新的关联关系
        if (roleIdList != null && roleIdList.size() > 0){
            adminMapper.insertNewRelationsip(adminId,roleIdList);
        }

    }
}
